/**
 * 后台服务脚本 - 测试版本
 */

console.log('🚀 BACKGROUND SCRIPT V3.0 LOADING...');

// 生成UUID
function generateUUID() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        const r = Math.random() * 16 | 0;
        const v = c === 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}

// input(q)函数 - 严格按照你的Python代码
async function getInput(query) {
    // 如果query是数组，连接所有元素
    if (Array.isArray(query)) {
        query = query.join('');
    }

    // 如果query长度 <= 10，直接返回
    if (query.length <= 10) {
        return query;
    }

    // 如果query长度 > 10，返回前10字符的MD5
    const first10 = query.substring(0, 10);
    return await md5(first10);
}

// MD5函数
async function md5(str) {
    const encoder = new TextEncoder();
    const data = encoder.encode(str);
    const hashBuffer = await crypto.subtle.digest('MD5', data);
    const hashArray = Array.from(new Uint8Array(hashBuffer));
    return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
}

// 生成v3签名 - 使用Base64编码（不使用input()函数，因为Base64通常很长）
async function generateSignWithBase64(base64Query, salt, curtime, appKey, appSecret) {
    console.log('🔐 V3 BASE64 SIGN GENERATION START');
    console.log('🔐 Parameters:', {
        appKey: appKey.substring(0, 8) + '...',
        base64QueryLength: base64Query.length,
        base64QueryPreview: base64Query.substring(0, 50) + (base64Query.length > 50 ? '...' : ''),
        salt: salt,
        curtime: curtime,
        appSecret: appSecret.substring(0, 8) + '...'
    });

    // 对于Base64编码的文本，直接使用，不再应用input()函数
    // 因为Base64编码后的文本不包含特殊字符，且长度通常>10
    // 如果需要严格遵循Python代码，可以在这里使用input()函数
    const inputQ = base64Query;

    console.log('🔐 Using Base64 directly (no input() function needed):', {
        originalLength: base64Query.length,
        finalLength: inputQ.length,
        finalPreview: inputQ.substring(0, 20) + (inputQ.length > 20 ? '...' : '')
    });

    // 签名算法：sha256(appKey + input(q) + salt + curtime + appSecret)
    const str = appKey + inputQ + salt + curtime + appSecret;
    console.log('🔐 Signature string length:', str.length);
    console.log('🔐 Signature string preview:', str.substring(0, 50) + (str.length > 50 ? '...' : ''));
    console.log('🔐 Contains newlines:', str.includes('\n'));

    // Python的hashlib.sha256(str.encode('utf8')).hexdigest() 在JavaScript中的等价实现
    const encoder = new TextEncoder(); // UTF-8 编码
    const data = encoder.encode(str);
    const hashBuffer = await crypto.subtle.digest('SHA-256', data);
    const hashArray = Array.from(new Uint8Array(hashBuffer));
    const sign = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');

    console.log('🔐 Generated signature length:', sign.length);
    console.log('🔐 Generated signature:', sign.substring(0, 20) + '...');
    console.log('🔐 BASE64 SIGN GENERATION END');
    return sign;
}

// 创建超时信号（兼容性处理）
function createTimeoutSignal(timeoutMs) {
    // 如果浏览器支持 AbortSignal.timeout，直接使用
    if (typeof AbortSignal.timeout === 'function') {
        return AbortSignal.timeout(timeoutMs);
    }

    // 否则手动实现超时
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), timeoutMs);

    // 在fetch完成后清除超时
    const originalSignal = controller.signal;
    originalSignal.addEventListener('abort', () => clearTimeout(timeoutId));

    return originalSignal;
}

// 生成v3签名 - 严格按照你的Python代码中的input()函数（保留备用）
async function generateSign(query, salt, curtime, appKey, appSecret) {
    console.log('🔐 V3 SIGN GENERATION START');
    console.log('🔐 Parameters:', {
        appKey: appKey.substring(0, 8) + '...',
        queryLength: query.length,
        queryPreview: query.substring(0, 50) + (query.length > 50 ? '...' : ''),
        salt: salt,
        curtime: curtime,
        appSecret: appSecret.substring(0, 8) + '...'
    });

    // 关键：input(q)函数 - 按照你的Python代码实现
    // 如果q是10字符以内，直接返回q；否则返回q的前10字符的MD5
    const inputQ = await getInput(query);
    console.log('🔐 input(q) result:', {
        originalLength: query.length,
        inputLength: inputQ.length,
        inputPreview: inputQ.substring(0, 20) + (inputQ.length > 20 ? '...' : '')
    });

    // 你的Python代码：sha256(appKey + input(q) + salt + curtime + appSecret)
    const str = appKey + inputQ + salt + curtime + appSecret;
    console.log('🔐 Signature string length:', str.length);
    console.log('🔐 Signature string preview:', str.substring(0, 50) + (str.length > 50 ? '...' : ''));
    console.log('🔐 Contains newlines:', str.includes('\n'));

    // Python的hashlib.sha256(str.encode('utf8')).hexdigest() 在JavaScript中的等价实现
    const encoder = new TextEncoder(); // UTF-8 编码
    const data = encoder.encode(str);
    const hashBuffer = await crypto.subtle.digest('SHA-256', data);
    const hashArray = Array.from(new Uint8Array(hashBuffer));
    const sign = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');

    console.log('🔐 Generated signature length:', sign.length);
    console.log('🔐 Generated signature:', sign.substring(0, 20) + '...');
    console.log('🔐 SIGN GENERATION END');
    return sign;
}

// 生成v3签名 - 严格按照你的Python代码（保留备用）
async function generateSign(query, salt, curtime, appKey, appSecret) {
    console.log('🔐 V3 SIGN GENERATION START');
    console.log('🔐 Parameters:', {
        appKey: appKey.substring(0, 8) + '...',
        queryLength: query.length,
        queryPreview: query.substring(0, 50) + (query.length > 50 ? '...' : ''),
        salt: salt,
        curtime: curtime,
        appSecret: appSecret.substring(0, 8) + '...'
    });

    // 你的Python代码：sha256(appKey + input(q) + salt + curtime + appSecret)
    const str = appKey + query + salt + curtime + appSecret;
    console.log('🔐 Signature string length:', str.length);
    console.log('🔐 Signature string preview:', JSON.stringify(str.substring(0, 50) + (str.length > 50 ? '...' : '')));
    console.log('🔐 Contains newlines:', str.includes('\n'));

    // Python的hashlib.sha256(str.encode('utf8')).hexdigest() 在JavaScript中的等价实现
    const encoder = new TextEncoder(); // UTF-8 编码
    const data = encoder.encode(str);
    const hashBuffer = await crypto.subtle.digest('SHA-256', data);
    const hashArray = Array.from(new Uint8Array(hashBuffer));
    const sign = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');

    console.log('🔐 Generated signature length:', sign.length);
    console.log('🔐 Generated signature:', sign.substring(0, 20) + '...');
    console.log('🔐 SIGN GENERATION END');
    return sign;
}

// 翻译文本 - 现在支持复杂文本
async function translateText(text, from, to) {
    console.log('🔄 ===== TRANSLATE TEXT START =====');
    console.log('🔄 Input:', {
        textLength: text.length,
        from: from,
        to: to,
        textPreview: text.substring(0, 50) + (text.length > 50 ? '...' : '')
    });

    const config = await chrome.storage.sync.get({
        translationEngine: 'openai',
        openaiApiKey: '',
        openaiBaseUrl: 'https://api.openai.com/v1',
        openaiModel: 'gpt-3.5-turbo',
        youdaoApiKey: '',
        youdaoAppSecret: ''
    });

    console.log('🔧 Translation engine:', config.translationEngine);
    console.log('🔧 Config loaded:', {
        engine: config.translationEngine,
        hasOpenApiKey: !!config.openaiApiKey,
        openApiKeyLength: config.openaiApiKey?.length,
        hasYoudaoApiKey: !!config.youdaoApiKey,
        youdaoApiKeyLength: config.youdaoApiKey?.length,
        hasAppSecret: !!config.youdaoAppSecret,
        appSecretLength: config.youdaoAppSecret?.length
    });

    // 根据选择的翻译引擎进行翻译
    if (config.translationEngine === 'openai') {
        return await translateWithOpenAI(text, from, to, config);
    } else if (config.translationEngine === 'youdao') {
        return await translateWithYoudao(text, from, to, config);
    } else {
        throw new Error(`不支持的翻译引擎: ${config.translationEngine}`);
    }
}

// OpenAI翻译函数
async function translateWithOpenAI(text, from, to, config) {
    console.log('🤖 ===== OPENAI TRANSLATION START =====');

    if (!config.openaiApiKey) {
        throw new Error('OpenAI API Key 未配置');
    }

    const languageMap = {
        'zh-CN': '简体中文',
        'zh-TW': '繁体中文',
        'en': '英语',
        'ja': '日语',
        'ru': '俄语',
        'auto': '自动检测'
    };

    const targetLanguage = languageMap[to] || '简体中文';
    const sourceLanguage = from === 'auto' ? '自动检测' : (languageMap[from] || '英语');

    const prompt = `请将以下${sourceLanguage}的算法竞赛题目内容翻译成${targetLanguage}。

要求：
1. 保持代码块、公式、数字不变
2. 保持原文的专业术语准确性
3. 保持段落结构清晰
4. 只返回翻译结果，不要添加额外说明

原文：
${text}

翻译：`;

    try {
        console.log('🌐 Sending OpenAI API request...');
        console.log('📋 Request details:', {
            model: config.openaiModel,
            baseUrl: config.openaiBaseUrl,
            textLength: text.length,
            from: from,
            to: to
        });

        const response = await fetch(`${config.openaiBaseUrl}/chat/completions`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${config.openaiApiKey}`
            },
            body: JSON.stringify({
                model: config.openaiModel,
                messages: [{ role: 'user', content: prompt }],
                max_tokens: Math.max(text.length * 2, 500),
                temperature: 0.3
            }),
            signal: createTimeoutSignal(30000)
        });

        console.log('📥 OpenAI response status:', response.status);

        if (!response.ok) {
            const error = await response.json();
            throw new Error(error.error?.message || `HTTP ${response.status}`);
        }

        const data = await response.json();
        const translation = data.choices[0]?.message?.content?.trim() || '';

        console.log('✅ OpenAI translation successful');
        return translation;

    } catch (error) {
        console.error('❌ OpenAI translation error:', error);
        throw error;
    }
}

// 有道翻译函数
async function translateWithYoudao(text, from, to, config) {
    console.log('🔤 ===== YOUDAO TRANSLATION START =====');

    if (!config.youdaoApiKey || !config.youdaoAppSecret) {
        throw new Error('有道翻译配置不完整');
    }

    // Base64编码方案：彻底消除换行符和特殊字符问题
    const originalText = text;

    // 1. 将待翻译文本转换成Base64编码格式
    let base64Text = btoa(unescape(encodeURIComponent(originalText)));

    console.log('🔧 Base64编码方案（标准Base64）:');
    console.log('  Original text length:', originalText.length);
    console.log('  Base64 text length:', base64Text.length);
    console.log('  Original preview:', JSON.stringify(originalText.substring(0, 50) + '...'));
    console.log('  Base64 preview:', base64Text.substring(0, 50) + '...');

    // 检查长度限制 - 检查Base64长度
    const MAX_LENGTH = 4000; // 保守的长度限制
    let finalBase64 = base64Text;
    if (base64Text.length > MAX_LENGTH) {
        console.log('🔧 Base64 too long, truncating to', MAX_LENGTH, 'characters');
        finalBase64 = base64Text.substring(0, MAX_LENGTH);
    }

    console.log('🔧 Final Base64 length for signature:', finalBase64.length);

    // 2. 用Base64编码格式去签名
    const salt = generateUUID();
    const curtime = Math.floor(Date.now() / 1000).toString();
    const sign = await generateSignWithBase64(finalBase64, salt, curtime, config.youdaoApiKey, config.youdaoAppSecret);

    // 3. 发请求时直接拼字符串，避免URL二次编码
    const body =
        `q=${finalBase64}&type=data&from=${from}&to=${to}` +
        `&appKey=${config.youdaoApiKey}&salt=${salt}&curtime=${curtime}&sign=${sign}&signType=v3`;

    console.log('🌐 Sending Youdao API request with Base64 + type=data...');
    console.log('📋 Request details:', {
        base64TextLength: finalBase64.length,
        originalTextLength: originalText.length,
        from: from,
        to: to,
        salt: salt,
        curtime: curtime,
        signLength: sign.length,
        hasTypeData: true
    });

    try {
        const response = await fetch('https://openapi.youdao.com/api', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: body
        });

        console.log('📥 Youdao response status:', response.status);
        const data = await response.json();
        console.log('📋 Youdao response data:', data);

        if (data.errorCode === '0') {
            console.log('✅ Youdao translation successful');
            return data.translation[0];
        } else {
            const errorMessages = {
                '108': 'appKey无效',
                '202': '签名检验失败',
                '301': '账户余额不足',
                '411': '访问频率受限',
                '501': '请求的query为空',
                '901': '翻译语种不支持'
            };
            const errorMsg = errorMessages[data.errorCode] || `API Error ${data.errorCode}`;
            console.error('❌ Youdao API error:', data.errorCode, errorMsg);
            throw new Error(errorMsg);
        }

    } catch (error) {
        console.error('❌ Youdao translation error:', error);
        throw error;
    }
}

// 消息监听器
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    console.log('📬 ===== MESSAGE RECEIVED (V3.0) =====');
    console.log('📬 Action:', request.action);
    console.log('🚨 THIS IS THE NEW VERSION - MODIFICATIONS ARE WORKING!');

    if (request.action === 'ping') {
        console.log('🏓 Ping received');
        sendResponse({
            success: true,
            message: 'pong'
        });
        return;
    }

    if (request.action === 'test') {
        console.log('🧪 Processing test request...');

        // 直接使用translateText函数进行测试
        translateText("Hello", 'en', 'zh-CHS')
            .then(translation => {
                console.log('✅ Test translation successful!');
                sendResponse({
                    success: true,
                    translation: translation
                });
            })
            .catch(error => {
                console.error('❌ Test translation failed:', error);
                sendResponse({
                    success: false,
                    error: error.message
                });
            });
        return true;
    }

    if (request.action === 'translate') {
        console.log('🔄 Processing translate request...');
        console.log('📋 Data length:', request.data?.length);

        // 使用新的翻译函数
        translateText(request.data, 'auto', 'zh-CHS')
            .then(translation => {
                console.log('✅ Translation completed successfully!');
                sendResponse({
                    success: true,
                    translation: translation
                });
            })
            .catch(error => {
                console.error('❌ Translation failed:', error);
                sendResponse({
                    success: false,
                    error: error.message
                });
            });

        return true;
    }

    console.log('📤 Unknown action:', request.action);
    sendResponse({
        success: false,
        error: 'Unknown action'
    });
});

// 扩展安装监听器
chrome.runtime.onInstalled.addListener(() => {
    console.log('Extension installed/updated');
});

console.log('✅ BACKGROUND SCRIPT V3.0 LOADED SUCCESSFULLY');